﻿using System;
using System.Collections.ObjectModel;
using System.Data;
using System.Web.UI.WebControls;

using Sunyi.Project.WebPoint.BusinessLogic;
using Sunyi.Project.WebPoint.Common;
using Sunyi.Project.WebPoint.DataContract;
using Sunyi.Project.WebPoint.Resource;
using Sunyi.Project.WebPoint.WebControl;

namespace ActivitySystem.Web.Admin
{
    public partial class RolePermission : WebPointPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Request.QueryString.Count > 0)
                {
                    try
                    {
                        Guid roleId = new Guid(Request.Params[WebPointGlobalConstant.RoleId]);
                        Bind(roleId);
                    }
                    catch (Exception ex)
                    {
                        ExceptionHandler.Handle(this, ex);
                    }
                }
            }
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            Role role = null;
            RoleManager roleManager = new RoleManager();

            try
            {
                Guid roleId = new Guid(Request.Params[WebPointGlobalConstant.RoleId]);
                role = roleManager.Select(roleId);
                role.Permissions.Clear();
            }
            catch (Exception ex)
            {
                ExceptionHandler.Handle(this, ex);
                return;
            }

            Guid[] permissionIds = ViewState[WebPointGlobalConstant.PermissionId] as Guid[];

            if (role != null && permissionIds != null)
            {
                for (int i = 0; i < gvPagePermission.Rows.Count; i++)
                {
                    Guid pageId = new Guid(((Label)gvPagePermission.Rows[i].Cells[0].FindControl("lblPageId")).Text);

                    if (!role.Permissions.ContainsKey(pageId))
                    {
                        role.Permissions.Add(pageId, new Collection<Guid>());

                        for (int j = 0; j < permissionIds.Length; j++)
                        {
                            if (((CheckBox)gvPagePermission.Rows[i].Cells[j + 1].Controls[1]).Checked)
                            {
                                role.Permissions[pageId].Add(permissionIds[j]);
                            }
                        }
                    }
                }

                try
                {
                    roleManager.Save(role);

                    AuditLogger.Write(AuditLogOperationCode.Update, this.GetType().Name, role);

                    this.ShowClientMessage(WebResource.OP_UpdateRolePermissionSuccessful);
                }
                catch (Exception ex)
                {
                    ExceptionHandler.Handle(this, ex);
                }
            }
        }

        #region Private Method

        private void Bind(Guid roleId)
        {
            RoleManager roleManager = new RoleManager();
            Role role = roleManager.Select(roleId);

            if (role != null)
            {
                liRoleName.Text += role.RoleName;

                PageManager pageManager = new PageManager();
                var pages = pageManager.SelectAll();

                PermissionManager permissionManager = new PermissionManager();
                Collection<Permission> permissions = permissionManager.SelectAll();

                #region Construct DataSource schema

                DataTable dt = new DataTable();
                dt.Columns.Add(new DataColumn(WebPointGlobalConstant.PageId, typeof(Guid)));
                dt.Columns.Add(new DataColumn(WebPointGlobalConstant.PageName, typeof(string)));

                Guid[] permissionIds = new Guid[permissions.Count];
                for (int i = 0; i < permissions.Count; i++)
                {
                    // Don't display inactive permissions.
                    if (!permissions[i].IsActive) continue;

                    DataColumn dc = new DataColumn();
                    dc.ColumnName = permissions[i].PermissionName;
                    dc.DataType = typeof(bool);
                    dc.DefaultValue = false;
                    dt.Columns.Add(dc);

                    permissionIds[i] = permissions[i].Id;
                }

                // Put permission columns into view state.
                ViewState[WebPointGlobalConstant.PermissionId] = permissionIds;

                #endregion

                #region Generate Data for Binding

                foreach (var page in pages)
                {
                    // Don't display inactive pages.
                    if (!page.IsActive) continue;

                    DataRow dr = dt.NewRow();
                    dr[WebPointGlobalConstant.PageId] = page.Id;
                    dr[WebPointGlobalConstant.PageName] = page.Url;

                    if (role.Permissions.ContainsKey(page.Id))
                    {
                        Collection<Guid> pagePermissions = role.Permissions[page.Id];

                        foreach (Guid pagePermission in pagePermissions)
                        {
                            foreach (Permission permission in permissions)
                            {
                                if (permission.Id == pagePermission)
                                {
                                    dr[permission.PermissionName] = true;
                                    break;
                                }
                            }
                        }
                    }

                    dt.Rows.Add(dr);
                }

                #endregion

                gvPagePermission.DataSource = dt;
                gvPagePermission.DataBind();
            }
        }

        #endregion

        #region WebPointPage Member

        protected override void ApplyPermission()
        {
            if (!this.HasPermission(PermissionType.Update))
            {
                btnSubmit.Visible = false;
            }
        }

        #endregion
    }
}